# 读取联系人数据
contacts = []
with open("contacts.txt", "r", encoding="utf-8") as f:
    for line in f:
        # 分割每行数据为姓名、性别、邮箱
        name, gender, email = line.strip().split()
        # 提取邮箱的用户名和域名
        username, domain = email.split("@")
        contacts.append(
            {
                "name": name,
                "gender": gender,
                "email": email,
                "username": username,
                "domain": domain,
            }
        )

# 排序：先按域名（126.com在前），再按用户名
contacts.sort(key=lambda x: (x["domain"], x["username"]))

# 生成 emails.txt
with open("emails.txt", "w", encoding="utf-8") as f:
    for i, contact in enumerate(contacts):
        # 确定称呼（先生/女士）
        title = "先生" if contact["gender"] == "男" else "女士"
        # 写入内容
        f.write(f"to: <{contact['email']}>\n")
        f.write(f"尊敬的{contact['name']}{title}，您的会员资格即将到期，请及时续费。\n")
        # 除了最后一个联系人，都添加分隔线
        if i != len(contacts) - 1:
            f.write("---\n")
